import { invoke } from "@tauri-apps/api/core";
import { UnlistenFn } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";

export async function availablePorts() {
    return await invoke('available_ports') as string[];
}

let unlistenFn: UnlistenFn | null = null;

export async function open(name: string) {

    if (unlistenFn != null) {
        unlistenFn();
    }
    const fn = await getCurrentWindow().listen<number[]>('recv', (event) => {
        console.log(toString(event.payload));
    });
    unlistenFn = fn;

    await invoke('open', {
        name,
        baudRate: 115200,
    });
}

export async function isOpen() {
    return await invoke('is_open') as boolean;
}

export async function close() {
    await invoke('close');
}

export function toString(buf: number[]) {
    const decoder = new TextDecoder('utf-8');
    return decoder.decode(Uint8Array.from(buf));
}











